var express = require('express')
var {expressjwt} = require('express-jwt')
var jwt = require('jsonwebtoken')
var bodyparser = require('body-parser');
const mysql = require('mysql2');
const multer = require('multer')
const fs = require('fs')

var uploadMulter = multer({dest:'uploads/'});
const app = new express();
const secretKey = 'NodejsDemoSecretKey';

const db = mysql.createConnection({
    host: '1.14.248.193',
    port: 3308,
    user: 'root',
    password: '_root_',
    database: 'nodejs'
}).promise();


app.use(bodyparser.json())
app.use(
    expressjwt({
      secret: secretKey,
      algorithms: ["HS256"],
      getToken: (req)=>{
        if(req.headers['x-token']){
            return req.headers['x-token']
        }
        return null;
      }
    }).unless({ path: ["/dev-api/vue-admin-template/user/login"] })
);


app.get('/dev-api/vue-admin-template/user/info',async (req,res)=>{
    console.log('receive user info request');
    
    /*
        todo:: 自己设计数据库，从数据库中获取用户信息
    
    */

    const [rows,fields] = await db.query(`select * from sys_user where username=?`,[req.auth.username]);
    console.log('username ==' + req.auth.username);
    const user  = rows[0];   

    res.json({
        code:20000,
        data:{
            name: req.auth.username,
            roles:['admin'],
            avatar: user.avatar,
        }
    })
})

app.post('/dev-api/vue-admin-template/user/logout',(req,res)=>{
    res.json({
        code:20000,
        data:{}
    });
})


app.post('/dev-api/vue-admin-template/user/login', async (req,res)=>{
    console.log('receiver user login request....');

    /*
        todo:: 增加登陆的逻辑判断 

    */
    console.log(req.body)
    const [rows,fields] = await db.query(`select * from sys_user where username=? and password=?`,[req.body.username, req.body.password]);
    if(rows.length >0){
        const user = rows[0];
        var token = jwt.sign({ username: user.username }, secretKey, { algorithm: 'HS256'});
        res.json({
            code:20000,
            data:{
                token
            }
        })
    }else{
        res.json({
            code:50000,
            data:{
                token
            },
            message: '账号或者密码错误！'
        })        
    }


    

})

/** 文章分类API */
app.get('/dev-api/vue-admin-template/art/category/list',async (req,res)=>{
    const [rows,fields] = await db.query(`select * from art_category`);
    res.json({
        code:20000,
        data:rows,
        message:"查询成功"
    })
})

app.put('/dev-api/vue-admin-template/art/category/edit',async (req,res)=>{
    await db.execute(`update art_category set name=? , code=?  where id=?`,[ req.body.name, req.body.code, req.body.id ]);
    console.log('receive edit category request....');
    console.log(req.body)
    res.json({
        code:20000,
        data:[],
        message:"修改成功"
    })
})

app.delete('/dev-api/vue-admin-template/art/category/edit', async(req,res)=>{
    await db.execute(`delete from art_category where id=?`, [req.body.id])
    res.json({
        code: 20000,
        data:[],
        message:"删除成功"
    })
})


app.post('/dev-api/vue-admin-template/upload', uploadMulter.array('file'), async (req,res)=>{
    console.log('receive upload request!')
    let files = req.files
                                                                                                            
    for(f of files){
        console.log(f.filename, f.originalname, f.mimetype);
        fs.renameSync("./uploads/" + f.filename , "./uploads/" + f.filename + "." + f.mimetype.split('/')[1])

    }

    res.json({
        code: 20000,
        data:[],
        message:'上传成功！'
    })
})


app.post('/dev-api/vue-admin-template/art/article/edit', async(req,res)=>{
    console.log(req.body.content)
    /* todo::
        1. 对title 和 content 做校验判断，如果为空，则提示报错！
        2. 在该接口下同时实现 文章草稿的保存！
        3. 在前端实现定时保存草稿的功能 （每分钟保存一次）
    */
    await db.execute(`INSERT INTO art_article ( content,content_draft,title,author,status,create_time, update_time) 
                      VALUES (?,?,?,?,0,now(),now())`, 
            [req.body.content,req.body.content,req.body.title,req.auth.username])

    res.json({
        code: 20000,
        data:[],
        message: '保存成功！'
    })
})


app.listen(8787,()=>{
    console.log('Node Server has started at 8787')
})